package chixing.day19.pcp_demo;

public class PublicResource {
    private int number;

    public PublicResource() {
    }

    public PublicResource(int number) {
        this.number = number;
    }

    //生产者生产面包
    public synchronized void produce() {
        System.out.println("生产者抢占到了11111111111111111111111111111");
        if (number == 5) {//等于10不生产了
            System.out.println("生产者抢占到了，面包个数 number = " + number + "不生产了进入等待队列");
            try {
                this.wait();//让生产者进入等待队列
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        } else {//没到10个抢占到就接着生产
            number++;
            this.notify();//唤醒在等待队列的消费者消费
            System.out.println("-----------------生产者生产了一个面包，number=" + number);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }


    }

    //消费者消费面包
    public synchronized void consume() {
        System.out.println("消费者抢占到了2222222222222222222222222222222");
        if (number == 0) {//消费者不能消费了，进入等待队列
            System.out.println("消费者抢占到了，面包个 number = " + number + "不消费，进入等待队列");
            try {
                this.wait();//消费者进入等待队列
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        } else {
            number--;
            this.notify();//唤醒生产则会生产
            System.out.println("-----------------消费者消费类一个面包，number=" + number);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
